// 统一处理菜单列表数据
import { ref, reactive, unref } from "vue";
import type { Ref } from "vue";
// let tableData = reactive([]);
// // 请求数据
// let requestParams = reactive({
//   parentId: 0,
// });
// let getRes = async () => {
//   let res = await menu.menuList(0, {
//     pageNum: 1,
//     pageSize: 10,
//   });
// };
function useMenuList<
  P,
  R extends {
    list: any;
    pageNum: number;
    pageSize: number;
    total: number;
    totalPage: number;
  }
>(api: (data: P) => Promise<R>, queryParams?: P) {
  // 分页器
  let pagination = reactive({
    pageNum: 1,
    pageSize: 10,
    total: 0,
    totalPage: 0,
  });
  // 列表数据
  let tableData: Ref<R["list"]> = ref([]);
  // 获取数据函数
  async function getTableData() {
    let normalQueryParams = {} as P;
    if (typeof queryParams === "object") {
      for (let key in queryParams) {
        normalQueryParams[key] = unref(queryParams[key]);
      }
    }
    // 发起请求
    let result = await api({
      pageNum: pagination.pageNum,
      pageSize: pagination.pageSize,
      ...normalQueryParams,
    });
    tableData.value = result.list;
    pagination.pageNum = result.pageNum;
    pagination.pageSize = result.pageSize;
    pagination.total = result.total;
    pagination.totalPage = result.totalPage;
  }
  getTableData();
  // 每条数据发送变时的处理
  let handleSizeChange = (val: number) => {
    pagination.pageSize = val;
    getTableData();
  };
  // 改变当前页数
  let handleCurrentChange = (val: number) => {
    pagination.pageNum = val;
    getTableData();
  };
  return {
    getTableData,
    tableData,
    pagination,
    handleSizeChange,
    handleCurrentChange,
  };
}

export default useMenuList;
